import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 模拟阻塞队列：
 * 一个向队列里面取数据、一个向队列里面存数据
 * 队列满了之后形成排队的阻塞
 */
public class EmulateBoundedBuffer {

	public static void main(String[] args) {
		
	}
	
	class BoundedBuffer {
		
		private Object [] items = new Object[100];
		private int putPos,getPos,count;
		private Lock lock = new ReentrantLock();
		private Condition full = lock.newCondition();  
		private Condition empty = lock.newCondition();  
		
		public void put(Object data) {
			lock.lock();
			try{
				while(count == items.length){
					try {
						full.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				items[putPos] = data;
				if(++putPos == items.length) putPos = 0;
				++count;
				empty.signal(); //通知另一个condition唤醒
			}finally{
				lock.unlock();
			}
			
		}
		
		public Object get() {
			lock.lock();
			try{
				while(count == 0) {
					try {
						empty.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Object x = items[getPos];
				if(++getPos == items.length) getPos = 0;
				--count;
				full.signal();
				return x;
			}finally{
				lock.unlock();
			}
			
		}
		
	}

}
